<template>
  <div>
    <div class="d_top">
      <div class="d_img">
        <img class="i_master" :src="order.order.avatar_url">
      </div>
      <div class="d_content">
        <p class="p_top_name">{{order.order.nick_name}}</p>
        <div class="d_content_item">
          <img class="i_product" :src="order.bargain.product_picture_url">
          <p class="p_product_name">【{{order.bargain.title}}】{{order.bargain.product_name}}</p>
          <p class="p_product_price">￥{{order.bargain.price/100}}</p>
          <p class="p_product_num">已有{{order.bargain.sale_num}}人{{order.bargain.target_price/100}}元拿</p>
        </div>
      </div>
    </div>

    <!-- 砍价中 -->
    <div v-if="order.order.status=='process'">
      <p class="p_center">
        已砍
        <span
          style="font-size:25px;color:#FFF059;margin:10px 0px;"
        >{{order.order.discount_amount/100}}</span>元，还差
        <span
          style="color:#FFF059;"
        >{{(order.bargain.price-order.bargain.target_price-order.order.discount_amount)/100}}</span>元
      </p>
      <van-row gutter="15" v-if="user.id==order.order.user_id">
        <van-col span="12">
          <button class="btn_pay" type="primary" @click="pay_hidden=false">支付{{(order.bargain.price-order.order.discount_amount)/100}}元购买</button>
        </van-col>
        <van-col span="12">
          <button class="btn_share" open-type="share">好友帮砍</button>
        </van-col>
      </van-row>
      <div v-if="!is_bargain">
        <button class="btn_help" @click="handleHelp">{{help_text}}</button>
      </div>
      <p class="p_center1" v-else>你已经砍过价了哦</p>
      <!-- <button class="btn_help" @click="handleHelp">{{help_text}}</button> -->
      <p class="p_center1">还剩{{count_down}}结束，快来砍价吧~</p>
    </div>

    <!-- 砍价成功 -->
    <div v-if="order.order.status=='success'">
      <p class="p_center1">砍价已完成</p>
      <button
        class="btn_help"
        @click="pay_hidden=false"
        v-if="order.bargain.target_price>0&&order.order.pay_status!='success'"
      >支付{{order.bargain.target_price/100}}元拿</button>

      <!-- 支付成功，线下物品可查看物流进度 -->
      <div style="margin:0px 15px;" v-if="order.order.pay_status=='success'">
        <van-steps :steps="steps" :active="active"/>
      </div>
    </div>

    <div v-if="order.order.status=='fail'">
      <button class="btn_help" @click="handleAgain">砍价失败，再试一次吧</button>
    </div>

    <div class="d_bottom">
      <p class="p_title">砍价榜</p>
      <p class="line"></p>
      <div v-for="(v,i) in order.records" :key="i">
        <div class="d_item">
          <img class="img" :src="v.user_avatar_url">
          <p class="p_name">{{v.user_name}}</p>
          <p class="p_right">砍掉{{v.cut_price/100}}元</p>
        </div>
      </div>
    </div>

    <modal
      :hidden="pay_hidden"
      title="选择支付方式"
      confirm-text="支付"
      cancel-text="取消"
      @cancel="pay_hidden=true"
      @confirm="handlePay"
    >
      <radio-group class="radio-group" @change="onChange" v-model="pay_type">
        <label class="radio">
          <p style="padding:10px 0px;">
            <radio value="wechat_pay" checked="true"/>微信支付
          </p>
        </label>
        <label class="radio" v-if="user.is_vip=='Y'">
          <p style="padding:10px 0px;border-top:1px solid #ccc;">
            <radio value="card_pay"/>会员支付
          </p>
        </label>
      </radio-group>
    </modal>
  </div>
</template>

<script>
import api from "@/utils/api";
import { mapState, mapActions, mapGetters } from "vuex";
export default {
  data() {
    return {
      steps: [
        {
          text: "已下单",bargain_status:'ordered'
        },
        {
          text: "已发货",bargain_status:'shipped'
        },
        {
          text: "已完成",bargain_status:'finish'
        },
        {
          text: "已取消",bargain_status:'cancel'
        },
        // {
        //   text: "已收货"
        // }
      ],
      active: 2,
      order_id: 0,
      order: {
        order: {},
        bargain: {},
        records: []
      },
      count_down: "",
      timer: "",
      countDownNum: 60,
      is_bargain: false,
      help_text: "帮他砍价",
      intervarID: 0,
      pay_type: "wechat_pay",
      items: [
        { name: "微信支付", value: "wechat_pay", checked: "true" },
        { name: "会员卡支付", value: "card_pay" }
      ],
      pay_hidden: true
    };
  },
  computed: {
    ...mapGetters(["login_info", "user"])
  },
  onPullDownRefresh() {
    // 下拉刷新
    // this.search.page=1
    this.fetchOrder();
  },
  onShareAppMessage(res) {
    return {
      title: "江湖救急，快来帮我砍价吧",
      path: "/pages/activity/kanjia_detail?order_id=" + this.order_id
    };
  },
  onUnload() {
    (this.active = 0), (this.pay_hidden = true);
  },
  methods: {
    ...mapActions(["refreshUser"]),
    onChange(e) {
      console.log(e);
      this.pay_type = e.target.value;
    },
    handlePay() {
      let self=this
      api
        .payBargainOrder({ order_id: this.order_id, pay_type: this.pay_type })
        .then(res => {
          if (res.code == 0) {
            if (self.pay_type == "wechat_pay") {
              wx.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                success(result) {
                  wx.showToast({
                    title: "支付成功",
                    icon: "success"
                  });
                  self.refreshUser();
                  self.pay_hidden = true;
                  self.fetchOrder();
                  // wx.redirectTo({
                  //   url: "order_detail?order_id=" + res.data.order_id
                  // });
                },
                fail(result) {
                  console.log("支付失败：", result);
                }
              });
            } else {
              wx.showToast({
                title: "支付成功",
                icon: "success"
              });
              self.pay_hidden = true;
              self.fetchOrder();
              self.refreshUser();
              // wx.redirectTo({
              //   url: "order_detail?order_id=" + res.data.order_id
              // });
            }
          }
        });
    },
    fetchOrder() {
      let self = this;
      api.getBargainOrder({ id: this.order_id }).then(res => {
        wx.stopPullDownRefresh();
        if (res.code == 0 && res.data) {
          self.order = {};
          self.order = res.data;

          if (self.order.order.status == "process") {
            if (self.order.order.user_id == self.user.id) {
              self.help_text = "自砍一刀";
            }

            // 判断是否砍过价
            if (self.order.records) {
              self.order.records.forEach(v => {
                if (v.user_id == self.user.id) {
                  self.is_bargain = true;
                }
              });
            }

            self.intervarID = setInterval(function() {
              var leftTime = new Date(self.order.order.end_time) - new Date(); //计算剩余的毫秒数
              var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
              var hours = parseInt((leftTime / 1000 / 60 / 60) % 24, 10); //计算剩余的小时
              var minutes = parseInt((leftTime / 1000 / 60) % 60, 10); //计算剩余的分钟
              var seconds = parseInt((leftTime / 1000) % 60, 10); //计算剩余的秒数
              days = self.checkTime(days);
              hours = self.checkTime(hours);
              minutes = self.checkTime(minutes);
              seconds = self.checkTime(seconds);
              self.count_down =
                days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
              if (
                days == "00" &&
                hours == "00" &&
                minutes == "00" &&
                seconds == "00"
              ) {
                clearInterval(self.intervarID);
              }
            }, 1000);
          }

          console.log("status", self.order.order.status);
          // 物流进度
          self.active = null;
          console.log("self.order.order.bargain_status", self.order.order.bargain_status);
          self.steps.forEach((v,i)=>{
            console.log(v,i)
            if(v.bargain_status==self.order.order.bargain_status){
              self.active=i
            }
          })
          // switch (self.order.order.bargain_status) {
          //   case "success":
          //     self.active = 2;
          //     break;
          //   case "delivery":
          //     self.active = 1;
          //     break;
          //   case "not_delivery":
          //     self.active = 0;
          //     break;
          // }
          console.log("active", self.active);
        }
      });
    },
    checkTime(val) {
      if (val > 9) {
        return val;
      } else {
        return "0" + val;
      }
    },
    log(title, obj) {
      console.log("kanjia_detail", title, obj);
    },
    handleHelp() {
      let self = this;
      api
        .helpBargain({ user_id: this.user.id, order_id: this.order_id })
        .then(res => {
          if (res.code == 0) {
            self.fetchOrder();
          }
        });
    },
    handleAgain() {
      wx.switchTab({
        url: "index?num=2"
      });
      // wx.navigateTo({url:})
    }
  },
  beforeMount() {
    if (!this.user || !this.user.id) {
      wx.redirectTo({
        url:
          "../user/get_user_info?callback_url=../activity/kanjia_detail&scene=" +
          this.order_id
      });
      return;
    }
    this.log("user", this.user);
  },
  mounted() {
    this.fetchOrder();
    // this.user.id = 1;
  },
  onLoad(param) {
    this.log("param", param);
    if (param) {
      if (param.scene) {
        this.order_id = param.scene;
      }
      if (param.order_id) {
        this.order_id = param.order_id;
      }
    }
  },
  onUnload() {
    this.order = {
      order: {},
      bargain: {},
      records: []
    };
    this.is_bargain = false;
    if (this.intervarID != 0) {
      clearInterval(this.intervarID);
    }
  }
};
</script>

<style>
page {
  background: red;
}

.d_bottom {
  background: #fd5252;
  margin: 10px 15px;
  border-radius: 5px;
  padding: 10px;
}

.p_title {
  font-size: 16px;
  text-align: center;
  vertical-align: middle;
  color: #fff;
}

.p_name {
  position: absolute;
  left: 55px;
  top: 0;
  color: #fff;
  font-size: 14px;
}

.p_right {
  position: absolute;
  bottom: 0px;
  right: 0px;
  color: #fdee59;
  font-size: 16px;
  line-height: 50px;
  vertical-align: middle;
  text-align: center;
}

.p_product_name {
  position: absolute;
  left: 100px;
  top: 10px;
  font-size: 16px;
  text-align: center;
  vertical-align: middle;
  color: #787878;
}

.p_product_price {
  position: absolute;
  left: 110px;
  bottom: 10px;
  color: red;
  font-size: 14px;
}

.p_product_num {
  position: absolute;
  right: 10px;
  bottom: 10px;
  color: #787878;
  font-size: 15px;
}

.line {
  margin: 5px 0px;
  border-top: solid 1px #ff6162;
}
.img {
  width: 50px;
  height: 50px;
  position: absolute;
  left: 0;
  top: 0;
}

.i_product {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0;
  top: 0;
}
.d_item {
  width: 100%;
  position: relative;
  height: 50px;
  margin-bottom: 5px;
}
/* 顶部 */
.d_top {
  position: relative;
  height: 200px;
  margin: 0px 15px;
}
.d_img {
  text-align: center;
  vertical-align: middle;
  width: 100%;
  position: absolute;
  top: 10px;
}
.i_master {
  width: 60px;
  height: 60px;
}
.d_content {
  background: #fff;
  border-radius: 5px;
  height: 160px;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  display: block;
  z-index: -1;
}
.p_top_name {
  text-align: center;
  vertical-align: middle;
  width: 100%;
  margin-top: 30px;
}
.d_content_item {
  padding: 5px;
  margin: 0px 10px;
  background: #f2f2f2;
  border-radius: 5px;
  position: relative;
  height: 90px;
}

.p_center {
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 10px;
}
.p_center1 {
  font-size: 14px;
  color: white;
  text-align: center;
  padding: 10px;
}
.btn_pay {
  margin-left: 15px;
}
.btn_share {
  margin-right: 15px;
  color: red;
  background: #fdee59;
}
.btn_help {
  margin: 10px 15px;
  color: red;
  background: #fdee59;
}
</style>
